package com.ruoyi.system.service.impl;

import java.util.*;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IAiRecordingDuanService;

/**
 * AI录音记录每一段（多条组成）Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-06
 */
@Service
public class AiRecordingDuanServiceImpl implements IAiRecordingDuanService
{
    @Autowired
    private AiRecordingDuanMapper aiRecordingDuanMapper;
    @Autowired
    private AiRecordingChildMapper aiRecordingChildMapper;
    @Autowired
    private AiDeepseekAnswerMapper aiDeepseekAnswerMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private AiDeepseekSpokesmanMapper aiDeepseekSpokesmanMapper;
    @Autowired
    private AiRecordingMainMapper aiRecordingMainMapper;
    /**
     * 查询AI录音记录每一段（多条组成）
     *
     * @param id AI录音记录每一段（多条组成）主键
     * @return AI录音记录每一段（多条组成）
     */
    @Override
    public AiRecordingDuan selectAiRecordingDuanById(Long id)
    {

        AiRecordingDuan aiRecordingDuan=  aiRecordingDuanMapper.selectAiRecordingDuanById(id);

        List<AiRecordingChild>  aiRecordingChildList=  aiRecordingChildMapper.selectChildBySpokes(aiRecordingDuan);
//        aiRecordingChildList.forEach(child->{
//            if (child.getFilePath().contains(".wav")){
//                child.setFilePath(child.getFilePath().split(".wav")[0]);
//            }
//        });
        aiRecordingDuan.setAiRecordingChildList(aiRecordingChildList);
        AiDeepseekAnswer aiDeepseekAnswer=new AiDeepseekAnswer();
        aiDeepseekAnswer.setMainId(aiRecordingDuan.getMainId());
        aiDeepseekAnswer.setDuanId(aiRecordingDuan.getId());
        List<AiDeepseekAnswer> aiDeepseekAnswerList= aiDeepseekAnswerMapper.selectAiDeepseekAnswerList(aiDeepseekAnswer);

//                //根据scoreYear字段进行分组
//                Map<String, List<AiDeepseekAnswer>> map = aiDeepseekAnswerList.stream().collect(
//                        Collectors.groupingBy(
//                                score -> score.getBatchId()
//                        ));
//                duan.setAnswerMap(map);
        aiRecordingDuan.setAiDeepseekAnswerList(aiDeepseekAnswerList);

        return aiRecordingDuan;
    }


    public String selectReward(){
         Long userId= SecurityUtils.getUserId();
        Double todayTime=  aiRecordingDuanMapper.selectReward(userId);

        Double result = (todayTime / 60); // 除以 60

        int sum=  ((int) Math.floor(result))*20;

        if (sum>=200){
            result= 200.0;
            return "今天已获得奖励200元";
        }else{
            Double str =60- todayTime % 60;
            return "今天已获得奖励"+sum+"元,再有"+str+"分钟即可再获得20元";
        }
    }

    public String selectRewardDay(){
        Long userId= SecurityUtils.getUserId();
        Double todayTimePrivate=  aiRecordingDuanMapper.selectReward(userId);

        RewardVo todayTimeOne=  aiRecordingDuanMapper.selectRewardDay();

        if (todayTimeOne==null){
            return "今天还没有人上传";
        }else{
            if (Objects.equals(todayTimeOne.getUserId(), userId)){
                return "恭喜你是第一名";
            }else{
                double difference = todayTimeOne.getValidTime() - todayTimePrivate;
                return "距离第一名还差"+difference+"分钟";
            }
        }

    }
    public String selectRewardSum(){
        Long userId= SecurityUtils.getUserId();
        Double todayTimePrivate=  aiRecordingDuanMapper.selectRewardSum(userId);
        if (todayTimePrivate==null){
            todayTimePrivate=0.0;
        }
        List<RewardVo> rewardVoList=  aiRecordingDuanMapper.selectRewardDaySum();
        if (!rewardVoList.isEmpty()){
            if (rewardVoList.size()>=1 && userId.equals(rewardVoList.get(0).getUserId())){
                return "800元奖励进行中";
            }else if (rewardVoList.size()>=2 &&   userId.equals(rewardVoList.get(1).getUserId())){
                return "500元奖励进行中，距离第一名差"+(rewardVoList.get(0).getValidTime()-todayTimePrivate)+"分钟";
            }else if ( rewardVoList.size()>=3 &&  userId.equals(rewardVoList.get(2).getUserId())){
                return "300元奖励进行中，距离第二名差"+(rewardVoList.get(1).getValidTime()-todayTimePrivate)+"分钟";
            }else {
                return "距离第三名差"+(rewardVoList.get(2).getValidTime()-todayTimePrivate)+"分钟";
            }
        }else{
            return "还没有人上传";
        }
    }



    /**
     * 查询AI录音记录每一段（多条组成）列表
     *
     * @param aiRecordingDuan AI录音记录每一段（多条组成）
     * @return AI录音记录每一段（多条组成）
     */
    @Override
    public List<AiRecordingDuan> selectAiRecordingDuanList(AiRecordingDuan aiRecordingDuan)
    {

//          List<Map<Integer,String>> mapList=new ArrayList<>();
//
//        AiRecordingDuan aiRecordingDuan1=new AiRecordingDuan();
//        List<AiRecordingDuan> aiRecordingDuanList=  aiRecordingDuanMapper.selectAiRecordingDuanList(aiRecordingDuan1);
//        final Integer[] iii = {0};
//        aiRecordingDuanList.forEach(duan->{
//
//            if (duan.getCustomerId()!=23L && duan.getCustomerId()!= 38L){
//                iii[0] = iii[0] +1;
//                Map<Integer,String> map=new HashMap<>();
////                map.keySet(iii);
//
//                AiDeepseekSpokesman aiDeepseekSpokesman =new AiDeepseekSpokesman();
//                aiDeepseekSpokesman.setDuanId(duan.getId());
//                List<AiDeepseekSpokesman>  aiDeepseekSpokesmanList= aiDeepseekSpokesmanMapper.selectAiDeepseekSpokesmanList(aiDeepseekSpokesman);
//                final String[] ton = {""};
//                aiDeepseekSpokesmanList.forEach(spoke->{
//                      if (spoke.getSpeaker()==null || spoke.getSpeaker().isEmpty()){
//                          spoke.setSpeaker("其他");
//                      }
//                    AiRecordingChild aiRecordingChild=  aiRecordingChildMapper.selectAiRecordingChildById(spoke.getChildId());
//                    ton[0] = ton[0] +spoke.getSpeaker()+":"+aiRecordingChild.getTranscript()+"\n";
//
//
//                });
//                map.put(iii[0], ton[0]);
//                mapList.add(map);
//            }
//
//
//
//
//        });
//        System.out.println(mapList.toString());
//
//        String json = JSON.toJSONString(mapList);
//--------------------22222222222222222222222222222222222222222222------------------------
//        AiRecordingMain aiRecordingMain=new AiRecordingMain();
//        aiRecordingMain.setStatus("3");
//        List<AiRecordingMain> aiRecordingMainList=  aiRecordingMainMapper.selectAiRecordingMainList(aiRecordingMain);
//        List<Map<String,String>> mapList=new ArrayList<>();
//        aiRecordingMainList.forEach(main->{
//
////            mapList
//            AiRecordingChild aiRecordingChild=new AiRecordingChild();
//            aiRecordingChild.setMainId(main.getId());
//            aiRecordingChild.setDelFlag("0");
//            List<AiRecordingChild> aiRecordingChildList=  aiRecordingChildMapper.selectAiRecordingChildList(aiRecordingChild);
//            final String[] con = {""};
//            Map<String,String> map=new HashMap<>();
//            aiRecordingChildList.forEach(child->{
//                con[0] = con[0] +child.getRl()+":"+child.getTranscript()+"\n";
//            });
//            map.put("创建人："+main.getCreateBy()+",创建时间："+main.getCreateTime(), con[0]);
//            mapList.add(map);
//
//        });
//        System.out.println(mapList.toString());
//
//        String json = JSON.toJSONString(mapList);






        Long userId= SecurityUtils.getUserId();
        SysUserRole sysUserRole =new SysUserRole();
        sysUserRole.setRoleId(100L);
        sysUserRole.setUserId(userId);
        Integer coun= sysUserRoleMapper.countUserRoleByRoleIdUserId(sysUserRole);
        if (coun == 0 && userId!=1L){
            aiRecordingDuan.setUserId(userId);
        }

        PageUtils.startPage();
        return aiRecordingDuanMapper.selectAiRecordingDuanList(aiRecordingDuan);
    }

    /**
     * 新增AI录音记录每一段（多条组成）
     *
     * @param aiRecordingDuan AI录音记录每一段（多条组成）
     * @return 结果
     */
    @Override
    public int insertAiRecordingDuan(AiRecordingDuan aiRecordingDuan)
    {
        aiRecordingDuan.setCreateTime(DateUtils.getNowDate());
        return aiRecordingDuanMapper.insertAiRecordingDuan(aiRecordingDuan);
    }

    /**
     * 修改AI录音记录每一段（多条组成）
     *
     * @param aiRecordingDuan AI录音记录每一段（多条组成）
     * @return 结果
     */
    @Override
    public int updateAiRecordingDuan(AiRecordingDuan aiRecordingDuan)
    {
        aiRecordingDuan.setUpdateTime(DateUtils.getNowDate());
        return aiRecordingDuanMapper.updateAiRecordingDuan(aiRecordingDuan);
    }

    /**
     * 批量删除AI录音记录每一段（多条组成）
     *
     * @param ids 需要删除的AI录音记录每一段（多条组成）主键
     * @return 结果
     */
    @Override
    public int deleteAiRecordingDuanByIds(Long[] ids)
    {
        return aiRecordingDuanMapper.deleteAiRecordingDuanByIds(ids);
    }

    /**
     * 删除AI录音记录每一段（多条组成）信息
     *
     * @param id AI录音记录每一段（多条组成）主键
     * @return 结果
     */
    @Override
    public int deleteAiRecordingDuanById(Long id)
    {
        return aiRecordingDuanMapper.deleteAiRecordingDuanById(id);
    }
}
